package com.hnmqet.demo01.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hnmqet.demo01.dao.AccountTblMapper;
import com.hnmqet.demo01.entity.AccountTbl;
import com.hnmqet.demo01.feign.OrderClint;
import com.hnmqet.demo01.feign.StorageApi;
import com.hnmqet.demo01.service.AccountTblService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalLock;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author td
 * @since 2020-01-02
 */
@Service
@Slf4j
public class AccountTblServiceImpl extends ServiceImpl<AccountTblMapper, AccountTbl> implements AccountTblService {
    @Autowired
    AccountTblMapper accountTblMapper;
    @Autowired
    OrderClint orderClint;
    @Autowired
    StorageApi storageApi;

    @Override
    @Transactional
   // @GlobalTransactional(rollbackFor = Throwable.class, timeoutMills = 300000)
    public void test() throws InterruptedException {
        log.info("Assign Service Begin ... xid: " + RootContext.getXID() + "\n");
        //1.创建账户 扣款
        AccountTbl accountTbl = accountTblMapper.selectById(12);
        AccountTbl accountTbl1 = accountTbl.setMoney(accountTbl.getMoney() - 1);
        accountTblMapper.updateById(accountTbl1);
        //2.创建订单
        orderClint.insert(accountTbl.getUserId() + "", "iphone11", 1 + "");
        //3.扣库存
        storageApi.decrease("iphone11", 1);
        //模拟异常
        //int i = 5 / 0;
        //TimeUnit.SECONDS.sleep(5);
    }

    @Override
    //@GlobalTransactional(rollbackFor = Throwable.class, timeoutMills = 300000)
    @GlobalLock
    public void batchUpdate() {
        log.info("Assign Service Begin ... xid: " + RootContext.getXID() + "\n");

        AccountTbl accountTbl=new AccountTbl();
        accountTbl.setMoney(1000);
        accountTbl.setUserId("123456");

        for (int i = 0; i < 100; i++) {
            log.info("Assign Service Begin ... xid: " + RootContext.getXID() + "\n");
            accountTblMapper.insert(accountTbl);
            orderClint.batchUpdate();

        }
    }

    @Override
    public void insetMore(List<AccountTbl> list) {
        this.saveBatch(list);
    }
}
